<template>
  <div class="system-management-container">
    <el-tabs v-model="activeTab" class="system-tabs">
      <el-tab-pane label="管理员管理" name="admins">
        <el-card class="management-card">
          <template #header>
            <div class="card-header">
              <span>管理员管理</span>
              <el-button type="primary" @click="showCreateAdminDialog">添加管理员</el-button>
            </div>
          </template>
          
          <!-- 管理员筛选 -->
          <el-form :model="adminFilterForm" label-width="80px" class="filter-form">
            <el-row :gutter="20">
              <el-col :span="6">
                <el-form-item label="院区">
                  <el-select
                    v-model="adminFilterForm.campus_id"
                    placeholder="请选择院区"
                    clearable
                    style="width: 100%"
                  >
                    <el-option
                      v-for="campus in campuses"
                      :key="campus.id"
                      :label="campus.name"
                      :value="campus.id"
                    />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="状态">
                  <el-select
                    v-model="adminFilterForm.status"
                    placeholder="请选择状态"
                    clearable
                    style="width: 100%"
                  >
                    <el-option label="启用" value="active" />
                    <el-option label="禁用" value="disabled" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12" style="text-align: right">
                <el-button type="primary" @click="searchAdmins">查询</el-button>
                <el-button @click="resetAdminFilters">重置</el-button>
              </el-col>
            </el-row>
          </el-form>
          
          <!-- 管理员列表 -->
          <el-table
            :data="admins"
            stripe
            style="width: 100%"
            v-loading="adminLoading"
            element-loading-text="加载中..."
          >
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="username" label="用户名" width="120" />
            <el-table-column prop="name" label="姓名" width="120" />
            <el-table-column prop="campus_name" label="所属院区" width="150" />
            <el-table-column prop="phone" label="手机号" width="120" />
            <el-table-column prop="status" label="状态" width="100">
              <template #default="{ row }">
                <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
                  {{ row.status === 'active' ? '启用' : '禁用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column prop="created_at" label="创建时间" width="180">
              <template #default="{ row }">
                {{ formatDate(row.created_at) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="{ row }">
                <el-button size="small" @click="showEditAdminDialog(row)">编辑</el-button>
                <el-button size="small" type="danger" @click="deleteAdmin(row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 管理员分页 -->
          <el-pagination
            v-model:current-page="adminPagination.page"
            v-model:page-size="adminPagination.size"
            :total="adminPagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="[10, 20, 50, 100]"
            @size-change="handleAdminSizeChange"
            @current-change="handleAdminCurrentChange"
            class="pagination"
          />
        </el-card>
      </el-tab-pane>
      
      <el-tab-pane label="院区管理" name="campuses">
        <el-card class="management-card">
          <template #header>
            <div class="card-header">
              <span>院区管理</span>
              <el-button type="primary" @click="showCreateCampusDialog">添加院区</el-button>
            </div>
          </template>
          
          <!-- 院区列表 -->
          <el-table
            :data="campuses"
            stripe
            style="width: 100%"
            v-loading="campusLoading"
            element-loading-text="加载中..."
          >
            <el-table-column prop="id" label="ID" width="80" />
            <el-table-column prop="name" label="院区名称" width="150" />
            <el-table-column prop="address" label="地址" show-overflow-tooltip />
            <el-table-column prop="contact_person" label="联系人" width="120" />
            <el-table-column prop="contact_phone" label="联系电话" width="120" />
            <el-table-column prop="created_at" label="创建时间" width="180">
              <template #default="{ row }">
                {{ formatDate(row.created_at) }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="150">
              <template #default="{ row }">
                <el-button size="small" @click="showEditCampusDialog(row)">编辑</el-button>
                <el-button size="small" type="danger" @click="deleteCampus(row.id)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 院区分页 -->
          <el-pagination
            v-model:current-page="campusPagination.page"
            v-model:page-size="campusPagination.size"
            :total="campusPagination.total"
            layout="total, sizes, prev, pager, next, jumper"
            :page-sizes="[10, 20, 50, 100]"
            @size-change="handleCampusSizeChange"
            @current-change="handleCampusCurrentChange"
            class="pagination"
          />
        </el-card>
      </el-tab-pane>
    </el-tabs>
    
    <!-- 添加/编辑管理员对话框 -->
    <el-dialog
      v-model="adminDialogVisible"
      :title="editingAdmin ? '编辑管理员' : '添加管理员'"
      width="500px"
    >
      <el-form
        ref="adminFormRef"
        :model="adminForm"
        :rules="adminFormRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input
            v-model="adminForm.username"
            :disabled="!!editingAdmin"
            placeholder="请输入用户名"
          />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="adminForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!editingAdmin">
          <el-input
            v-model="adminForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword" v-if="!editingAdmin">
          <el-input
            v-model="adminForm.confirmPassword"
            type="password"
            placeholder="请确认密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="adminForm.phone" placeholder="请输入手机号" />
        </el-form-item>
        <el-form-item label="所属院区" prop="campus_id">
          <el-select
            v-model="adminForm.campus_id"
            placeholder="请选择院区"
            style="width: 100%"
          >
            <el-option
              v-for="campus in campuses"
              :key="campus.id"
              :label="campus.name"
              :value="campus.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="adminForm.status">
            <el-radio label="active">启用</el-radio>
            <el-radio label="disabled">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="adminDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveAdmin">保存</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 添加/编辑院区对话框 -->
    <el-dialog
      v-model="campusDialogVisible"
      :title="editingCampus ? '编辑院区' : '添加院区'"
      width="500px"
    >
      <el-form
        ref="campusFormRef"
        :model="campusForm"
        :rules="campusFormRules"
        label-width="80px"
      >
        <el-form-item label="院区名称" prop="name">
          <el-input v-model="campusForm.name" placeholder="请输入院区名称" />
        </el-form-item>
        <el-form-item label="地址" prop="address">
          <el-input
            v-model="campusForm.address"
            type="textarea"
            placeholder="请输入地址"
          />
        </el-form-item>
        <el-form-item label="联系人" prop="contact_person">
          <el-input v-model="campusForm.contact_person" placeholder="请输入联系人" />
        </el-form-item>
        <el-form-item label="联系电话" prop="contact_phone">
          <el-input v-model="campusForm.contact_phone" placeholder="请输入联系电话" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="campusDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveCampus">保存</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { superAdminApi } from '../../api/superadmin'
import type { Admin, Campus, AdminRequest, CampusRequest } from '../../types/superadmin'
import { showError, showSuccess } from '@/utils/message'
import { formatDate } from '@/utils/date'
import type { FormInstance, FormRules } from 'element-plus'

// 当前激活的标签页
const activeTab = ref('admins')

// 管理员相关数据
const admins = ref<Admin[]>([])
const adminLoading = ref(false)
const adminDialogVisible = ref(false)
const editingAdmin = ref<Admin | null>(null)

// 院区相关数据
const campuses = ref<Campus[]>([])
const campusLoading = ref(false)
const campusDialogVisible = ref(false)
const editingCampus = ref<Campus | null>(null)

// 管理员筛选表单
const adminFilterForm = reactive({
  campus_id: undefined as number | undefined,
  status: ''
})

// 管理员分页参数
const adminPagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 院区分页参数
const campusPagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 管理员表单
const adminForm = reactive({
  username: '',
  name: '',
  password: '',
  confirmPassword: '',
  phone: '',
  campus_id: undefined as number | undefined,
  status: 'active'
})

// 院区表单
const campusForm = reactive({
  name: '',
  address: '',
  contact_person: '',
  contact_phone: ''
})

// 管理员表单引用
const adminFormRef = ref<FormInstance>()

// 院区表单引用
const campusFormRef = ref<FormInstance>()

// 管理员表单验证规则
const adminFormRules = reactive<FormRules>({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 50, message: '用户名长度为3-50个字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入姓名', trigger: 'blur' },
    { min: 1, max: 100, message: '姓名长度为1-100个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 50, message: '密码长度为6-50个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== adminForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的手机号', trigger: 'blur' }
  ],
  campus_id: [
    { required: true, message: '请选择所属院区', trigger: 'change' }
  ]
})

// 院区表单验证规则
const campusFormRules = reactive<FormRules>({
  name: [
    { required: true, message: '请输入院区名称', trigger: 'blur' },
    { min: 1, max: 100, message: '院区名称长度为1-100个字符', trigger: 'blur' }
  ],
  contact_phone: [
    { pattern: /^1[3-9]\d{9}$/, message: '请输入正确的联系电话', trigger: 'blur' }
  ]
})

/**
 * 获取管理员列表
 */
const getAdmins = async () => {
  try {
    adminLoading.value = true
    
    const params: { page?: number; size?: number; campus_id?: number; status?: string } = {
      page: adminPagination.page,
      size: adminPagination.size,
      ...(adminFilterForm.campus_id !== undefined && { campus_id: adminFilterForm.campus_id }),
      ...(adminFilterForm.status && { status: adminFilterForm.status })
    }
    
    // 注意：由于响应拦截器已经处理了响应格式，这里直接获取数据
    const response = await superAdminApi.getAdmins(params)
    admins.value = response.items || []
    adminPagination.total = response.total || 0
  } catch (error) {
    console.error('获取管理员列表失败:', error)
    showError('获取管理员列表失败')
  } finally {
    adminLoading.value = false
  }
}

/**
 * 获取院区列表
 */
const getCampuses = async () => {
  try {
    campusLoading.value = true
    
    const params = {
      page: campusPagination.page,
      size: campusPagination.size
    }
    
    // 注意：由于响应拦截器已经处理了响应格式，这里直接获取数据
    const response = await superAdminApi.getCampuses(params)
    campuses.value = response.items || []
    campusPagination.total = response.total || 0
  } catch (error) {
    console.error('获取院区列表失败:', error)
    showError('获取院区列表失败')
  } finally {
    campusLoading.value = false
  }
}

/**
 * 查询管理员
 */
const searchAdmins = () => {
  adminPagination.page = 1
  getAdmins()
}

/**
 * 重置管理员筛选条件
 */
const resetAdminFilters = () => {
  adminFilterForm.campus_id = undefined
  adminFilterForm.status = ''
  adminPagination.page = 1
  getAdmins()
}

/**
 * 处理管理员分页大小变化
 */
const handleAdminSizeChange = (size: number) => {
  adminPagination.size = size
  adminPagination.page = 1
  getAdmins()
}

/**
 * 处理管理员当前页变化
 */
const handleAdminCurrentChange = (page: number) => {
  adminPagination.page = page
  getAdmins()
}

/**
 * 处理院区分页大小变化
 */
const handleCampusSizeChange = (size: number) => {
  campusPagination.size = size
  campusPagination.page = 1
  getCampuses()
}

/**
 * 处理院区当前页变化
 */
const handleCampusCurrentChange = (page: number) => {
  campusPagination.page = page
  getCampuses()
}

/**
 * 显示创建管理员对话框
 */
const showCreateAdminDialog = () => {
  editingAdmin.value = null
  adminForm.username = ''
  adminForm.name = ''
  adminForm.password = ''
  adminForm.confirmPassword = ''
  adminForm.phone = ''
  adminForm.campus_id = undefined
  adminForm.status = 'active'
  adminDialogVisible.value = true
}

/**
 * 显示编辑管理员对话框
 */
const showEditAdminDialog = (admin: Admin) => {
  editingAdmin.value = admin
  adminForm.username = admin.username
  adminForm.name = admin.name
  adminForm.password = ''
  adminForm.confirmPassword = ''
  adminForm.phone = admin.phone || ''
  adminForm.campus_id = admin.campus_id
  adminForm.status = admin.status
  adminDialogVisible.value = true
}

/**
 * 保存管理员
 */
const saveAdmin = async () => {
  if (!adminFormRef.value) return
  
  await adminFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      const adminData: AdminRequest = {
        username: adminForm.username,
        name: adminForm.name,
        ...(adminForm.phone && { phone: adminForm.phone }),
        ...(adminForm.campus_id && { campus_id: adminForm.campus_id }),
        status: adminForm.status as 'active' | 'disabled'
      }
      
      if (editingAdmin.value) {
        // 更新管理员
        const response = await superAdminApi.updateAdmin(editingAdmin.value.id, adminData)
        // 注意：由于响应拦截器已经处理了错误情况，这里只会接收到成功的响应
        showSuccess('更新管理员成功')
        adminDialogVisible.value = false
        getAdmins()
      } else {
        // 创建管理员
        adminData.password = adminForm.password
        const response = await superAdminApi.createAdmin(adminData)
        // 注意：由于响应拦截器已经处理了错误情况，这里只会接收到成功的响应
        showSuccess('创建管理员成功')
        adminDialogVisible.value = false
        getAdmins()
      }
    } catch (error) {
      // 错误已经被响应拦截器处理并显示，这里只需要记录日志
      console.error('保存管理员失败:', error)
    }
  })
}

/**
 * 删除管理员
 */
const deleteAdmin = async (adminId: number) => {
  try {
    await superAdminApi.deleteAdmin(adminId)
    showSuccess('删除管理员成功')
    getAdmins()
  } catch (error) {
    console.error('删除管理员失败:', error)
    showError('删除管理员失败')
  }
}

/**
 * 显示创建院区对话框
 */
const showCreateCampusDialog = () => {
  editingCampus.value = null
  campusForm.name = ''
  campusForm.address = ''
  campusForm.contact_person = ''
  campusForm.contact_phone = ''
  campusDialogVisible.value = true
}

/**
 * 显示编辑院区对话框
 */
const showEditCampusDialog = (campus: Campus) => {
  editingCampus.value = campus
  campusForm.name = campus.name
  campusForm.address = campus.address || ''
  campusForm.contact_person = campus.contact_person || ''
  campusForm.contact_phone = campus.contact_phone || ''
  campusDialogVisible.value = true
}

/**
 * 保存院区
 */
const saveCampus = async () => {
  if (!campusFormRef.value) return
  
  await campusFormRef.value.validate(async (valid) => {
    if (!valid) return
    
    try {
      const campusData: CampusRequest = {
        name: campusForm.name,
        ...(campusForm.address && { address: campusForm.address }),
        ...(campusForm.contact_person && { contact_person: campusForm.contact_person }),
        ...(campusForm.contact_phone && { contact_phone: campusForm.contact_phone })
      }
      
      if (editingCampus.value) {
        // 更新院区
        const response = await superAdminApi.updateCampus(editingCampus.value.id, campusData)
        // 注意：由于响应拦截器已经处理了错误情况，这里只会接收到成功的响应
        showSuccess('更新院区成功')
        campusDialogVisible.value = false
        getCampuses()
      } else {
        // 创建院区
        const response = await superAdminApi.createCampus(campusData)
        // 注意：由于响应拦截器已经处理了错误情况，这里只会接收到成功的响应
        showSuccess('创建院区成功')
        campusDialogVisible.value = false
        getCampuses()
      }
    } catch (error) {
      // 错误已经被响应拦截器处理并显示，这里只需要记录日志
      console.error('保存院区失败:', error)
    }
  })
}

/**
 * 删除院区
 */
const deleteCampus = async (campusId: number) => {
  try {
    await superAdminApi.deleteCampus(campusId)
    showSuccess('删除院区成功')
    getCampuses()
  } catch (error) {
    console.error('删除院区失败:', error)
    showError('删除院区失败')
  }
}

// 组件挂载时加载数据
onMounted(() => {
  getAdmins()
  getCampuses()
})
</script>

<style scoped>
.system-management-container {
  padding: 20px;
}

.system-tabs {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.management-card {
  margin-top: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-form {
  margin-bottom: 20px;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>